package com.bnz.search.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.bnz.search.entity.ItemEntity;
import com.bnz.search.entity.ItemVo;
import com.bnz.search.service.ItemSearchService;
import org.elasticsearch.index.query.QueryBuilders;

import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//Es7.6版本。
//@Service
public class ItemSearchServiceImpl implements ItemSearchService {
    /**
     * 查询商评
     * @param vo
     * @return
     */
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Override
    public Map search(ItemVo vo) {
        //定义返回的map结果
        Map resultMap = new HashMap();
        //chuan建NativeSearchQueryBuilder
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
        if(vo != null){
            if(StrUtil.isNotBlank(vo.getKeywords())){
                //多字段查询
                searchQueryBuilder.withQuery(QueryBuilders.multiMatchQuery(vo.getKeywords(),"title","category","brand"));
                //进行高亮查询
//                searchQueryBuilder.withHighlightBuilder(new HighlightBuilder().preTags("<span style='color:red'>").postTags("</span>").field("title"));
            }
            NativeSearchQuery query = searchQueryBuilder.build();

            SearchHits<ItemEntity> searchHits = elasticsearchRestTemplate.search(query, ItemEntity.class, IndexCoordinates.of("item"));

            List<SearchHit<ItemEntity>> searchHitsList = searchHits.getSearchHits();
            List<ItemEntity> itemEntities = new ArrayList<>();
            for (SearchHit<ItemEntity> searchHit : searchHitsList) {
                //得到原始的数据
                ItemEntity content = searchHit.getContent();
                //得到高亮数据
//                List<String> title = searchHit.getHighlightField("title");
                //修改原始数据的高亮字段的值
//                content.setTitle(!CollectionUtils.isEmpty(title) ? title.get(0) : content.getTitle());
//                System.out.println("content = " + content);
                itemEntities.add(content);
            }

            resultMap.put("itemList",itemEntities);
        }

        return resultMap;
    }

}
